<template>
  <view class="new-or-edit-modal">
    <up-popup v-model:show="show" overlay mode="bottom" touchable maxHeight="'80%'" closeable closeOnClickOverlay
      @close="close" @open="open">
      <view class="modal-content">
        <view class="modal-header">
          <view class="modal-title">{{ title }}</view>
        </view>
        <up-tree :data="formModel.treeData" :props="defaultProps" show-checkbox default-expand-all
          @node-click="handleNodeClick" />
      </view>

      <view class="modal-footer">
        <up-button type="primary" @click="submit">确认</up-button>
      </view>
    </up-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue';

const defaultProps = ref({
  children: 'children',
  label: 'label',
  nodeKey: 'id'
});

const props = defineProps({
  type: {
    type: String,
    default: 'add',
  },
  rowData: {
    type: Object,
    default: () => { },
  }
})
defineOptions({ name: "PremissionModal" });

// 创建响应式数据  
const show = defineModel<boolean>("show", { default: false });

const formModel = ref(createDefaultModel());
function createDefaultModel() {
  return {
    treeData: []
  };
}
function handleInitModel() {
  formModel.value = createDefaultModel();
  if (!props.rowData) return;
  if (props.type === "edit") {
    Object.assign(formModel.value, props.rowData);
  }
}
const title = computed(() => {
  const titles: any = {
    add: "新增权限",
    edit: "编辑权限",
  };
  return titles[props.type];
});

const handleNodeClick = (node) => {
  console.log('节点被点击:', node);
};

const submit = async () => {
  console.log(formModel.value);
}

// 定义方法  
function open() {
  show.value = true;
  handleInitModel();
}

function close() {
  // 关闭逻辑，设置 show 为 false  
  show.value = false;
  console.log('close');
}  
</script>

<style scoped lang="scss">
.new-or-edit-modal {
  .modal-header {
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }

  .modal-content {
    padding: 20rpx;
  }
}
</style>
